﻿using Microsoft.AspNetCore.Mvc;
using Qy.Core;
using Qy.Scenario;
using Qy.Web.Authorize;
using System.Threading.Tasks;

namespace Qy.Web.Areas.Api;

[Route("Api/[controller]/[action]")]
[Verify]
public class DictCatController : Base
{
    private readonly DictDataService _dictDataService;
    private readonly DictCatService _dictCatService;
    public DictCatController(DictDataService dictDataService, DictCatService dictCatService)
    {
        _dictDataService = dictDataService;
        _dictCatService = dictCatService;
    }
    [HttpGet]
    [ActionPermissionFilter(Permission = PermissionKeys.Dict_Index)]
    public async Task<IActionResult> IndexAsync([FromQuery] QueryDictCat query)
    {
        PagedInfo<DictCat> pagedList = await _dictCatService.GetPageListAsync(query);
        return Success(new { count = pagedList.TotalNum, data = pagedList.Result });
    }
    [HttpGet]
    [ActionPermissionFilter(Permission = PermissionKeys.Dict_AddOrEditView)]
    public async Task<IActionResult> AddOrEditAsync(int id)
    {
        DictCat data = await _dictCatService.GetIdAsync(id);
        return Success(new { data });
    }

    [HttpPost, ActionName("Create")]
    [ModelStateFilter]
    [ActionPermissionFilter(Permission = PermissionKeys.Dict_AddOrEdit)]
    [Log(Name = "新增字典类别")]
    public async Task<IActionResult> CreatePostAsync([FromBody] DictCat dictCat)
    {
        if (await _dictCatService.InsertAndDelCacheAsync(dictCat) != null)
            return Success("新增字典类别: " + dictCat.CatName);
        else
            return Fail("失败，可能字典代码重复");
    }


    [HttpPut, ActionName("Edit")]
    [ModelStateFilter]
    [ActionPermissionFilter(Permission = PermissionKeys.Dict_AddOrEdit)]
    [Log(Name = "修改字典类别")]
    public async Task<IActionResult> EditPostAsync([FromBody] DictCat dictCat)
    {
        if (await _dictCatService.UpdateDelCache(dictCat) > 0)
            return Success("成功修改字典类别：" + dictCat.CatName);
        else
            return Fail("失败，可能字典代码重复");
    }

    [HttpDelete]
    [ActionPermissionFilter(Permission = PermissionKeys.Dict_Delete)]
    [Log(Name = "删除字典类别")]
    public async Task<IActionResult> Delete(int id)
    {
        if (await _dictCatService.DeleteDelCache(id))
            return Success("删除字典类别 ID：" + id);
        else
            return Fail("删除失败,可能该类别下有内容");
    }
}
